/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.engine.cmd.api;

import cn.easyplatform.dos.OrgDo;
import cn.easyplatform.dos.UserDo;
import cn.easyplatform.engine.cmd.task.BeginCmd;
import cn.easyplatform.entities.beans.project.DeviceMapBean;
import cn.easyplatform.i18n.I18N;
import cn.easyplatform.interceptor.AbstractCommand;
import cn.easyplatform.interceptor.Command;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.messages.request.BeginRequestMessage;
import cn.easyplatform.messages.response.SimpleResponseMessage;
import cn.easyplatform.messages.vos.EnvVo;
import cn.easyplatform.messages.vos.PageVo;
import cn.easyplatform.messages.vos.TaskVo;
import cn.easyplatform.type.*;
import cn.easyplatform.util.MessageUtils;
import cn.easyplatform.util.RuntimeUtils;
import org.apache.shiro.SecurityUtils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @Description:
 * @Since: 2.0.0 <br/>
 * @Date: Created in 2019/10/29 18:21
 * @Modified By:
 */
public class TaskCmd extends AbstractCommand<BeginRequestMessage> {

    public TaskCmd(BeginRequestMessage req) {
        super(req);
    }

    @Override
    public IResponseMessage<?> execute(CommandContext cc) {
        TaskVo tv = req.getBody();
        boolean normal = !"passport".equals(tv.getAgentId());
        if (normal) {
            if (cc.getUser() != null && cc.getUser().getType() >= UserType.TYPE_OAUTH)//防止不正常的调用
                return new SimpleResponseMessage("e200", I18N.getLabel("api.access.error"));
            cc.getEnv().setDeviceType(DeviceType.getType(tv.getAgentId()));
            cc.getUser().setDeviceType(cc.getEnv().getDeviceType());
            tv.setAgentId(null);
        } else if (cc.getUser() == null) {//第3方登陆
            UserDo guest = RuntimeUtils.createGustUser("oauth", UserType.TYPE_OAUTH, cc.getEnv(), cc.getProjectService());
            for (FieldVo f : tv.getVariables()) {
                if (f.getName().equals("ip")) {
                    guest.setIp((String) f.getValue());
                    break;
                }
            }
            cc.setUser(guest);
        }
        Command cmd = new BeginCmd(req);
        IResponseMessage<?> resp = cmd.execute(cc);
        if (!resp.isSuccess())
            return resp;
        if (tv.isGetEnv()) {
            Map<String, Object> data = new HashMap<>();
            data.put("result", resp.getBody());
            EnvVo env = new EnvVo();
            env.setProjectId(cc.getProjectService().getId());
            env.setSessionId(SecurityUtils.getSubject().getSession().getId());
            env.setDeviceType(cc.getUser().getDeviceType().getName());
            env.setAppContext(cc.getProjectService().getEntity().getAppContext());
            env.setTitle(cc.getProjectService().getDescription());
            DeviceMapBean dm = cc.getProjectService().getDeviceMap(env.getPortlet(), env.getDeviceType());
            if (dm == null)
                return MessageUtils.projectDeviceInvalid();
            if (Strings.isBlank(dm.getTheme()))
                env.setTheme(cc.getProjectService().getEntity().getTheme());
            else
                env.setTheme(dm.getTheme());
            env.setLanguages(cc.getProjectService().getLanguages());
            env.setLoginPage(dm.getLoginPage());
            data.put("env", env);
            return new SimpleResponseMessage(data);
        } else if ("passport".equals(tv.getAgentId())) {//第3方登陆
            if (resp.isSuccess()) {
                Object body = cc.remove("$passport");
                if (body == null)//用户没注册，显示注册页面
                    return resp;
                else//用户已授权登陆
                    return new SimpleResponseMessage(body);
            }
            return resp;
        } else
            return resp;
    }
}
